package com.leps.nq.common;

import cn.dev33.satoken.exception.*;
import cn.dev33.satoken.stp.StpUtil;
import com.leps.nq.common.exception.BadCredentialsException;
import com.leps.nq.common.exception.UserStatusDisabledException;
import com.leps.nq.common.vo.R;
import com.leps.nq.common.vo.RBuilder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public R<?> handleException(Exception e) {
        // 不同异常返回不同状态码
        R<?> resp;
        if (e instanceof BadCredentialsException) {
            resp = RBuilder.unauthenticated().setMsg("用户名或密码错误");
        } else if (e instanceof UserStatusDisabledException) {
            resp = RBuilder.unauthenticated().setMsg("此帐号已停用");
        } else if (e instanceof NotLoginException) {    // 如果是未登录异常
            resp = RBuilder.unauthenticated();
        } else if (e instanceof NotRoleException) {        // 如果是角色异常
            resp = RBuilder.unauthorized();
        } else if (e instanceof NotPermissionException) {    // 如果是权限异常
            resp = RBuilder.unauthorized();
        } else if (e instanceof DisableLoginException) {    // 如果是被封禁异常
            resp = RBuilder.unauthenticated().setMsg("帐号被封禁");
        } else if (e instanceof NotSafeException) {
            StpUtil.openSafe(120);
            resp = RBuilder.error("需二次身份认证");
        } else {
            e.printStackTrace();
            resp = RBuilder.error(e.getMessage());
        }
        // 返回给前端
        return resp;
    }
}
